package com.mingqijia.gassafety.webserver.service.workorder.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.gap.basic.exception.BizException;
import com.github.pagehelper.util.StringUtil;
import com.mingqijia.gassafety.authority.api.resp.config.DictionaryItemRespDTO;
import com.mingqijia.gassafety.authority.dal.helper.ConfigureHolder;
import com.mingqijia.gassafety.db.constant.DtuConstant;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.auth.CompanyEntry;
import com.mingqijia.gassafety.db.mapper.DepartmentMapper;
import com.mingqijia.gassafety.db.mapper.DtuBindingOrderMapper;
import com.mingqijia.gassafety.db.mapper.DtuMapper;
import com.mingqijia.gassafety.db.mapper.ServiceComboOrderMapper;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.utils.commonUtils.BeanConvertUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.DateUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.SnowflakeUtil;
import com.mingqijia.gassafety.webserver.request.inner.SyncOrderDataRespose;
import com.mingqijia.gassafety.webserver.request.workorder.asst.ContactsEditRequest;
import com.mingqijia.gassafety.webserver.request.workorder.asst.ContactsListRequest;
import com.mingqijia.gassafety.webserver.request.workorder.order.OrderSparkOrderRequest;
import com.mingqijia.gassafety.webserver.response.workorder.asst.ContactsListResponse;
import com.mingqijia.gassafety.webserver.service.*;
import com.mingqijia.gassafety.shared.constant.AsstConstants;
import com.mingqijia.gassafety.shared.constant.TemplateTypeEnum;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.utils.ApplicationUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.LocationUtil;
import com.mingqijia.gassafety.webserver.feign.ConsoleSkFeignClient;
import com.mingqijia.gassafety.webserver.request.*;
import com.mingqijia.gassafety.webserver.request.console.sk.ConsoleSkUpdateRequest;
import com.mingqijia.gassafety.webserver.request.workorder.asst.OrderCompleteRequest;
import com.mingqijia.gassafety.webserver.request.workorder.asst.OrderInfoSyncRequest;
import com.mingqijia.gassafety.webserver.response.VccUserRseponse;
import com.mingqijia.gassafety.webserver.response.sk.ConsoleSkUpdateResponse;
import com.mingqijia.gassafety.webserver.service.workorder.SyncNewAsstOrderService;
import com.mingqijia.gassafety.webserver.service.workorder.SyncOrderService;
import com.mingqijia.gassafety.webserver.service.workorder.WorkOrderHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.mingqijia.gassafety.shared.constant.Constants.*;
/**
 * @program: gassafety
 * @description:
 * @author: Mr.Wang
 * @create: 2022-09-19 14:38
 **/

@Service
@Slf4j
public class SyncOrderServiceImpl implements SyncOrderService {
    @Autowired
    private ConsumerService consumerService;
    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private DtuBindingOrderMapper dtuBindingOrderMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    WorkOrderHistoryService workOrderHistoryService;
    @Autowired
    AppealLogService appealLogService;
    @Autowired
    SmartKitchenLogService smartKitchenLogService;
    @Autowired
    HistoryAlarmService historyAlarmService;
    @Autowired
    HistoryBrokenService historyBrokenService;
    @Autowired
    ConsoleSkFeignClient client;
    @Autowired
    ConsumerLocationService consumerLocationService;
    @Autowired
    SyncNewAsstOrderService syncNewAsstOrderService;

    @Autowired
    DtuMapper dtuMapper;

    @Autowired
    LocationUtil locationUtil;

    @Autowired
    private ServiceComboOrderMapper serviceComboOrderMapper;

    @Autowired
    DictionaryService dictionaryService;

    @Autowired
    CompanyService companyService;

    @Autowired
    ConfigureHolder holder;

    @Autowired
    ContactsService contactsService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createConsumerBindImei(ConsumerCreateRequest request) {
        log.info("createConsumerBindImei-param:{}",JSONObject.toJSON(request));
        String spId = ApplicationUtils.getHeaderSpId();
        spId = dictionaryService.selectNewAsstSpMapping(spId);
        //判断该 用户id是否存在
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Consumer::getMemberId, request.getMemberId())
                .eq(Consumer::getIsDeleted, IS_DELETED_FALSE)
                .eq(Consumer::getSpId, spId);
        Consumer consumer = consumerService.getOne(queryWrapper);
        double doubleLat =0;
        double doubleLng =0;
        if (consumer != null) {
            // 用户被删除 or 用户已存在
            if (consumer.getIsDeleted()) { //用户被删除
                Consumer consumerNew = new Consumer();
                consumerNew.setIsDeleted(false);
                consumerNew.setId(consumer.getId());
                consumerNew.setCreatedAt(new Date());
                double[] location = locationUtil.baiDuUrlGeocoding(consumer.getCustAddress());
                //维度&经度
                doubleLat = location[0];
                doubleLng = location[1];
                consumerNew.setPositionLon(doubleLng);
                consumerNew.setPositionLat(doubleLat);
                consumerNew.setStatus(1);
                log.info("createConsumerBindImei-consumerNew:{}",JSONObject.toJSON(consumerNew));
                consumerService.updateById(consumerNew);
            }
        } else {
            // 用户不存在,创建对应客户
            //spId，去department表里查
            QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
            departmentQueryWrapper.lambda().eq(Department::getSpId, spId);
            Department department = departmentMapper.selectOne(departmentQueryWrapper);

            Consumer consumerAdd = new Consumer();
            consumerAdd.setName("");
            consumerAdd.setDepartmentId( department.getId() );
            consumerAdd.setPath( department.getPath() );
            consumerAdd.setMemberId(request.getMemberId());
            consumerAdd.setSource(2);
            consumerAdd.setTemplateType(BIND_CHANNEL_ASST);
            if (!StringUtils.isEmpty(request.getPhone())) {
                consumerAdd.setPhone(request.getPhone());
            }
            consumerAdd.setIndustryType("notFilled");
            consumerAdd.setSpId(spId);
            consumerAdd.setStatusAnyalert(false);
            consumerAdd.setStatusAnybroken(false);
            consumerAdd.setStatusAnyoffline(false);
            consumerAdd.setStatusAnynormal(true);
            consumerAdd.setStatusUpdatetime(new Date());
            consumerAdd.setStatus(1);
            //consumerNew.setOrgCode();
            log.info("createConsumerBindImei-consumerAdd:{}",JSONObject.toJSON(consumerAdd));
            consumerService.save(consumerAdd);
        }


        //获取客户id
        queryWrapper.lambda().eq(Consumer::getIsDeleted, false);
        Consumer consumerNow = consumerService.getOne(queryWrapper);
        log.info("客户id:{}", consumerNow.getId());
        consumerNow.setPositionLat(request.getPositionLat());
        consumerNow.setPositionLon(request.getPositionLon());
        consumerLocationService.updateConsumerLocation(consumerNow);
        
        //构建入参
        ConsumerBindingRequest bindingRequest = new ConsumerBindingRequest();
        List<BindingPositionRequest> list = new ArrayList<>();
        BindingPositionRequest bindingPositionRequest = new BindingPositionRequest();
        bindingPositionRequest.setImei(request.getImei());
        list.add(bindingPositionRequest);

        bindingRequest.setConsumerId(consumerNow.getId());
        bindingRequest.setImeiList(list);
        bindingRequest.setBindChannel(BIND_CHANNEL_ASST);
        bindingRequest.setOutOrderCode(request.getOutOrderCode());
        bindingRequest.setSource(0);
        bindingRequest.setPositionLon(doubleLng);
        bindingRequest.setPositionLat(doubleLat);
        log.info("客户绑定设备入参, ConsumerBindingRequest :{}", bindingRequest.toString());
        consumerService.bindingEquipment(bindingRequest);

        //由于地址可以修改,只能在完工提交时,同步设备安装信息

        //新增工单记录
        WorkOrderHistory workOrderHistory = new WorkOrderHistory();
        workOrderHistory.setDeviceId(request.getImei());
        workOrderHistory.setOrderNo(request.getOrderNo());
        workOrderHistory.setFromSystem(AsstConstants.FROM_SYSTEM_1);
        workOrderHistory.setSpId(spId);
        workOrderHistory.setOrderType(1);
        workOrderHistoryService.insertHistory(workOrderHistory);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createOrderConsumerBindImei(ConsumerCreateRequest request) {
        String spId = ApplicationUtils.getHeaderSpId();
        spId = dictionaryService.selectNewAsstSpMapping(spId);
        log.info("createOrderConsumerBindImei current use spId:{}",spId);

        // 根据设备的imei号查询到spid
        QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
        dtuQueryWrapper.lambda().eq(Dtu::getIMEI, request.getImei())
                .eq(Dtu::getIsDeleted, 0);
        Dtu dtu = equipmentService.getOne(dtuQueryWrapper);
        Consumer consumer = null;
        // 判断该 用户id是否存在
        QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
        if (dtu != null && dtu.getConsumerId() != null && dtu.getConsumerId() > 0) {
            // 判断该 用户id是否存在
            queryWrapper.lambda().eq(Consumer::getId, dtu.getConsumerId()).eq(Consumer::getSpId, spId)
                    .eq(Consumer::getIsDeleted, Constants.IS_DELETED_FALSE);
            consumer = consumerService.getOne(queryWrapper);
            if (consumer != null) {
                if (!StringUtils.isEmpty(consumer.getSubsCode())) {
                    if (!StringUtils.isEmpty(request.getSubsCode()) && !StringUtils.pathEquals(request.getSubsCode(), consumer.getSubsCode())) {
                        throw new BizException("该IMEI已绑定客户并且户号不同");
                    }
                } else if (!StringUtils.isEmpty(consumer.getMemberId()) && !StringUtils.isEmpty(request.getMemberId()) && !StringUtils.pathEquals(request.getMemberId(), consumer.getMemberId())) {
                    throw new BizException("该IMEI已绑定客户并且会员id不同");
                }
            }
            if (!StringUtils.isEmpty(request.getSubsCode())) {
                //判断该 户号是否存在
                QueryWrapper<Consumer> queryOrderWrapper = new QueryWrapper<>();
                queryOrderWrapper.lambda().eq(Consumer::getSubsCode, request.getSubsCode())
                        .eq(Consumer::getIsDeleted, IS_DELETED_FALSE)
                        .eq(Consumer::getSpId, spId);
                Consumer serviceOne = consumerService.getOne(queryOrderWrapper);
                if (consumer != null) {
                    if (serviceOne != null && !serviceOne.getId().equals(consumer.getId())) {
                        consumer.setIsDeleted(true);
                        consumerService.updateById(consumer);
                        dtu.setConsumerId(0);
                        dtu.setSectorType(Constants.BLANK);
                        dtuMapper.updateById(dtu);
                        consumer = serviceOne;
                    }
                } else if (serviceOne != null) {
                    consumer = serviceOne;
                }

            }
        } else if (!StringUtils.isEmpty(request.getSubsCode())) {
            //判断该 用户id是否存在
            queryWrapper.lambda().eq(Consumer::getSubsCode, request.getSubsCode())
                    .eq(Consumer::getIsDeleted, IS_DELETED_FALSE)
                    .eq(Consumer::getSpId, spId);
            consumer = consumerService.getOne(queryWrapper);
        }

        if (consumer != null) {
            Consumer consumerNew = new Consumer();
            consumerNew.setId(consumer.getId());
            consumerNew.setCreatedAt(new Date());
            if (StringUtils.isEmpty(consumer.getMemberId()) && !StringUtils.isEmpty(request.getMemberId())) {
                consumerNew.setMemberId(request.getMemberId());
            }

            consumerNew = formatConsumerFromVccUser(spId,request,consumerNew);

            consumerNew.setStatus(1);
            log.info("createConsumerBindImei-consumerNew:{}",JSONObject.toJSON(consumerNew));
            consumerService.updateById(consumerNew);
            consumer = consumerNew;
        } else {
            // 用户不存在,创建对应客户
            //spId，去department表里查
            QueryWrapper<Department> departmentQueryWrapper = new QueryWrapper<>();
            departmentQueryWrapper.lambda().eq(Department::getSpId, spId);
            Department department = departmentMapper.selectOne(departmentQueryWrapper);

            Consumer consumerAdd = new Consumer();
            consumerAdd.setName("");
            consumerAdd.setDepartmentId( department.getId() );
            consumerAdd.setPath( department.getPath() );
            consumerAdd.setMemberId(request.getMemberId());
            consumerAdd.setSource(2);
            consumerAdd.setTemplateType(BIND_CHANNEL_ASST);
            if (!StringUtils.isEmpty(request.getPhone())) {
                consumerAdd.setPhone(request.getPhone());
            }
            if (!StringUtils.isEmpty(request.getConsumerName())){
                consumerAdd.setName(request.getConsumerName());
            }
            if (!StringUtils.isEmpty(request.getConsumerAddress())){
                consumerAdd.setCustomerAddress(request.getConsumerAddress());
                consumerAdd.setAddress(request.getConsumerAddress());
            }

            consumerAdd = formatConsumerFromVccUser(spId,request,consumerAdd);

            consumerAdd.setIndustryType("notFilled");
            consumerAdd.setSpId(spId);
            consumerAdd.setStatusAnyalert(false);
            consumerAdd.setStatusAnybroken(false);
            consumerAdd.setStatusAnyoffline(false);
            consumerAdd.setStatusAnynormal(true);
            consumerAdd.setStatusUpdatetime(new Date());
            consumerAdd.setStatus(1);
            if (!spId.equals(ApplicationUtils.getHeaderSpId())) {
                CompanyEntry companyEntry = companyService.getBaseMapper().selectById(ApplicationUtils.getHeaderSpId());
                if (companyEntry != null && !companyEntry.getIsDeleted() && !StringUtils.isEmpty(companyEntry.getCode())) {
                    consumerAdd.setOrgCode(companyEntry.getCode());
                }
            }
            //consumerNew.setOrgCode();
            log.info("createConsumerBindImei-consumerAdd:{}",JSONObject.toJSON(consumerAdd));
            consumerService.save(consumerAdd);
            consumer = consumerAdd;
        }


        //获取客户id
        log.info("客户id:{}", consumer);
        consumerLocationService.updateConsumerLocation(consumer);

        double doubleLat = consumer.getPositionLat();
        double doubleLng = consumer.getPositionLon();

        //更新客户联系人中
        consumerService.updateContacts(consumer);

        //构建入参
        ConsumerBindingRequest bindingRequest = new ConsumerBindingRequest();
        List<BindingPositionRequest> list = new ArrayList<>();
        BindingPositionRequest bindingPositionRequest = new BindingPositionRequest();
        bindingPositionRequest.setImei(request.getImei());
        list.add(bindingPositionRequest);

        bindingRequest.setConsumerId(consumer.getId());
        bindingRequest.setImeiList(list);
        bindingRequest.setBindChannel(BIND_CHANNEL_ASST);
        bindingRequest.setOutOrderCode(request.getOutOrderCode());
        bindingRequest.setSource(0);
        bindingRequest.setPositionLon(doubleLng);
        bindingRequest.setPositionLat(doubleLat);
        bindingRequest.setSpId(spId);
        log.info("客户绑定设备入参, ConsumerBindingRequest :{}", JSONObject.toJSONString(bindingRequest));
        consumerService.bindingOrderEquipment(bindingRequest);

        //由于地址可以修改,只能在完工提交时,同步设备安装信息

        QueryWrapper<WorkOrderHistory> workOrderQueryWrapper = new QueryWrapper<>();
        workOrderQueryWrapper.lambda().eq(WorkOrderHistory::getOrderNo, request.getOrderNo())
                .eq(WorkOrderHistory::getSpId, spId)
                .eq(WorkOrderHistory::getIsDeleted, Constants.IS_DELETED_FALSE);
        WorkOrderHistory orderHistory = workOrderHistoryService.getOne(workOrderQueryWrapper);
        if (orderHistory != null) {
            orderHistory.setDeviceId(request.getImei());
            orderHistory.setConsumerId(consumer.getId());
            workOrderHistoryService.updateById(orderHistory);
        } else {
            //新增工单记录
            WorkOrderHistory workOrderHistory = new WorkOrderHistory();
            workOrderHistory.setDeviceId(request.getImei());
            workOrderHistory.setOrderNo(request.getOrderNo());
            workOrderHistory.setFromSystem(AsstConstants.FROM_SYSTEM_1);
            workOrderHistory.setConsumerId(consumer.getId());
            workOrderHistory.setSpId(spId);
            workOrderHistory.setOrderType(1);
            workOrderHistoryService.insertHistory(workOrderHistory);
        }

    }

    public Consumer formatConsumerFromVccUser(String spId,ConsumerCreateRequest request,Consumer consumerNew){
        double positionLat=0;
        double positionLon=0;
        if (!StringUtils.isEmpty(request.getSubsCode())) {
            VccUserRseponse vccUser = consumerService.getVccUser(request.getSubsCode(),spId,"");
            if (vccUser==null)
                throw  new BizException("户号:"+request.getSubsCode()+"vcc未查到");
            DictionaryItemRespDTO custTypeDict = holder.getDictionaryInMap(Constants.CUST_TYPE_ENUM).get(vccUser.getCustType());
            consumerNew.setSubsCode(vccUser.getSubsCode());
            consumerNew.setCustName(vccUser.getCustName());
            consumerNew.setCustAddress(vccUser.getCustAddress());
            consumerNew.setCustPhone(vccUser.getCustPhone());
            consumerNew.setCustType(custTypeDict.getName());
            consumerNew.setCustTypeCode(vccUser.getCustType());
            consumerNew.setCustStatus(CustStatusEnum.getCustStatusName(vccUser.getCustStatus()));
            String orgCode = "";
            if (!spId.equals(ApplicationUtils.getHeaderSpId())) {
                CompanyEntry companyEntry = companyService.getBaseMapper().selectById(ApplicationUtils.getHeaderSpId());
                if (companyEntry != null && !companyEntry.getIsDeleted() &&
                        !StringUtils.isEmpty(companyEntry.getCode())) {
                    orgCode = companyEntry.getCode();
                }
                consumerNew.setOrgCode(orgCode);
            }
            if (!StringUtils.isEmpty(request.getPositionLon())&&!StringUtils.isEmpty(request.getPositionLat())){
                positionLat = new BigDecimal(request.getPositionLat()).setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
                positionLon = new BigDecimal(request.getPositionLon()).setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
            }else if(!StringUtils.isEmpty(vccUser.getCustAddress())){
                String preAddr = "";
                try {
                    Dictionary dictionary = dictionaryService.selectValueByAlias(orgCode);
                    preAddr = dictionary.getDescription();
                }catch (Exception e){
                    log.info(e.getMessage());
                }
                double[] latLng = locationUtil.baiDuUrlGeocoding(preAddr+vccUser.getCustAddress());
                positionLat = latLng[0];
                positionLon = latLng[1];
            }
        }else if (!StringUtils.isEmpty(request.getPositionLon())&&!StringUtils.isEmpty(request.getPositionLat())){
            positionLat = new BigDecimal(request.getPositionLat()).setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
            positionLon = new BigDecimal(request.getPositionLon()).setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        consumerNew.setPositionLon(positionLon);
        consumerNew.setPositionLat(positionLat);
        return consumerNew;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void unbindEquipment(ConsumerUnbindRequest request) {
        String spId = ApplicationUtils.getHeaderSpId();
        spId = dictionaryService.selectNewAsstSpMapping(spId);
        log.info("ConsumerUnbindRequest current use spId:{}",spId);
        ConsumerunBindingRequest bindingRequest = new ConsumerunBindingRequest();
        bindingRequest.setImei(request.getImei());
        bindingRequest.setOutOrderCode(request.getOutOrderCode());
        bindingRequest.setTemplateType(TemplateTypeEnum.TEMPLATE_TYPE_2.getCode());
        bindingRequest.setBindChannel(BIND_CHANNEL_ASST);
        //根据 用户id查询对应客户id
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        consumerQueryWrapper.lambda().eq(Consumer::getMemberId, request.getMemberId())
                .eq(Consumer::getSpId,spId)
                .eq(Consumer::getIsDeleted, false);
        List<Consumer> consumers = consumerService.list(consumerQueryWrapper);
        if (CollectionUtil.isNotEmpty(consumers)){
            bindingRequest.setConsumerId(consumers.get(0).getId());
        }else {
            throw  new BizException("用户id:"+request.getMemberId()+",未创建客户");
        }
        //渠道一和渠道二走同一个解绑逻辑
        consumerService.unbindEquipment(bindingRequest);
        //解绑删除工单记录
        workOrderHistoryService.deleteHistory(request.getOrderNo(),request.getImei(),spId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String unbindOrderEquipment(ConsumerUnbindRequest request) {
        String spId = ApplicationUtils.getHeaderSpId();
        spId = dictionaryService.selectNewAsstSpMapping(spId);
        log.info("unbindOrderEquipment current use spId:{}",spId);

        ConsumerunBindingRequest bindingRequest = new ConsumerunBindingRequest();
        bindingRequest.setImei(request.getImei());
        bindingRequest.setOutOrderCode(request.getOutOrderCode());
        bindingRequest.setTemplateType(TemplateTypeEnum.TEMPLATE_TYPE_2.getCode());
        bindingRequest.setBindChannel(BIND_CHANNEL_ASST);
        bindingRequest.setMemberId(request.getMemberId());
        //根据 用户id查询对应客户id
        List<Consumer> consumers;
        QueryWrapper<Consumer> consumerQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(request.getSubsCode())) {
            consumerQueryWrapper.lambda().eq(Consumer::getSubsCode, request.getSubsCode())
                    .eq(Consumer::getSpId,spId)
                    .eq(Consumer::getIsDeleted, false);
            consumers = consumerService.list(consumerQueryWrapper);
            bindingRequest.setSubCode(request.getSubsCode());
        } else if (!StringUtils.isEmpty(request.getMemberId())){
            consumerQueryWrapper.lambda().eq(Consumer::getMemberId, request.getMemberId())
                    .eq(Consumer::getSpId,spId)
                    .eq(Consumer::getIsDeleted, false);
            consumers = consumerService.list(consumerQueryWrapper);
        } else {
            QueryWrapper<Dtu> dtuQueryWrapper = new QueryWrapper<>();
            dtuQueryWrapper.lambda().eq(Dtu::getIMEI, request.getImei())
                    .eq(Dtu::getSpId,spId)
                    .eq(Dtu::getIsDeleted, false);
            Dtu dtu = dtuMapper.selectOne(dtuQueryWrapper);
            if (dtu != null && dtu.getConsumerId() > 0) {
                consumerQueryWrapper.lambda().eq(Consumer::getId, dtu.getConsumerId())
                        .eq(Consumer::getSpId,spId)
                        .eq(Consumer::getIsDeleted, false);
                consumers = consumerService.list(consumerQueryWrapper);
            } else {
                return "已解绑";
            }
        }
        if (CollectionUtil.isNotEmpty(consumers)){
            bindingRequest.setConsumerId(consumers.get(0).getId());
        }else {
            bindingRequest.setSubCode(request.getSubsCode());
            throw  new BizException("用户id:"+request.getMemberId()+",未创建客户");

        }
        bindingRequest.setSpId(spId);
        //渠道一和渠道二走同一个解绑逻辑
        String msg = consumerService.unbindEquipmentOrder(bindingRequest);
        //解绑删除工单设备记录
        workOrderHistoryService.updateDeviceId(request.getOrderNo(),request.getImei(),spId);
        return msg;
    }

    @Override
    public void equipmentPosition(List<EquipmentPositionRequest> request) {
        String spId = ApplicationUtils.getHeaderSpId();
        spId = dictionaryService.selectNewAsstSpMapping(spId);
        for (EquipmentPositionRequest positionRequest : request) {
            //校验入参中 安装位置存在;
            if (StringUtil.isEmpty(positionRequest.getInstallationPosition())){
                throw new BizException("安装位置必填");
            }
            positionRequest.setTemplateType(BIND_CHANNEL_ASST);
            positionRequest.setSpId(spId);
            equipmentService.editPosition(positionRequest);
        }


    }

    @Override
    public void orderInfo(OrderInfoSyncRequest request) {
        log.info("OrderInfoSyncRequest = {}", JSONObject.toJSONString(request));
        String spId = ApplicationUtils.getWorkingSpId();
        spId = dictionaryService.selectNewAsstSpMapping(spId);
        log.info("unbindOrderEquipment current use spId:{}",spId);

        DtuBindingOrder order = new DtuBindingOrder();
        ArrayList<Dtu> dtus = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(request.getImeiList())){
            String installationAddress = new String();
            //同步设备的安装地址和经纬度
            if (StringUtil.isNotEmpty(request.getRealAddress())) {
                installationAddress = request.getRealAddress();
            } else {
                installationAddress = request.getAddress();
            }
            double[] location = locationUtil.baiDuUrlGeocoding(installationAddress);
            //维度&经度
            double doubleLat = location[0];
            double doubleLng = location[1];
            for (String imei : request.getImeiList()) {
                BeanUtil.copyProperties(request,order );
                order.setDeviceId(imei);
                //根据 用户id获得客户id
                QueryWrapper<Consumer> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(Consumer::getMemberId, request.getMemberId())
                        .eq(Consumer::getIsDeleted, IS_DELETED_FALSE)
                        .eq(Consumer::getSpId,spId );
                Consumer consumer = consumerService.getOne(queryWrapper);
                order.setConsumerId(consumer.getId());
                order.setSpId(spId);
                //判断该设备是否存在
                DtuBindingOrder orderOld = dtuBindingOrderMapper.selectByImei(imei, spId);
                if (orderOld !=null){
                    order.setId(orderOld.getId());
                    order.setIsDeleted(Boolean.FALSE);
                    dtuBindingOrderMapper.updateById(order);
                }else {
                    dtuBindingOrderMapper.insert(order);
                }


                Dtu dtu = new Dtu();
                dtu.setId(imei);
                dtu.setInstallationAddress(installationAddress);
                dtu.setPositionLat(doubleLat);
                dtu.setPositionLon(doubleLng);
                dtus.add(dtu);
            }
            log.info("设备更新安装地址和经纬度: {}", dtus.toString());
            equipmentService.updateBatchById(dtus);

            //判断是否是补录的同步
            if (!STR_ONE.equals(request.getIsAddRecord())){
                //同步工单信息 更新工单记录表-工单完成
                workOrderHistoryService.updateHandleStatus(request.getOrderNo(),1,null);
            }
        }
    }

    @Override
    @Transactional
    public void orderComplete(OrderCompleteRequest request) {
        LambdaQueryWrapper<WorkOrderHistory> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(WorkOrderHistory::getOrderNo,request.getOrderNo())
                .eq(WorkOrderHistory::getIsDeleted,0);
        if (null != request.getWorkSystem() && request.getWorkSystem()>0) {
            queryWrapper.eq(WorkOrderHistory::getWorkSystem, request.getWorkSystem());
        }
        WorkOrderHistory history = workOrderHistoryService.getOne(queryWrapper);
        if (history != null) {
            if (history.getOrderType() == 1) {
                if (!StringUtils.pathEquals("2", request.getCompleteResult())) {
                    //更新工单状
                    WorkOrderHistory workOrderHistory = new WorkOrderHistory();
                    workOrderHistory.setId(history.getId());
                    workOrderHistory.setHandleStatus(1);
                    workOrderHistory.setCompleteTime(request.getCompletedTime());
                    workOrderHistory.setDeviceId(request.getDeviceId());
                    workOrderHistory.setSpId(history.getSpId());
                    workOrderHistoryService.updateById(workOrderHistory);
                    workOrderHistory.setCreatedAt(history.getCreatedAt());
                    String installDate = request.getInstallDate();
                    if(org.apache.commons.lang.StringUtils.isNotEmpty(request.getDeviceId()) &&
                            history.getDeviceId().length() >= DtuConstant.IMEI_MIN_LENGTH) {
                        dtuMapper.updatePosition(request.getInstallPosition(),request.getDeviceId(), installDate);
                    }
                    if (history.getConsumerId() > 0) {
                        LambdaUpdateWrapper<Consumer> updateWrapper = new LambdaUpdateWrapper<>();
                        updateWrapper.or().eq(Consumer::getId, history.getConsumerId())
                                .set(Consumer::getStatus, 0);
                        consumerService.update(updateWrapper);
                    }
                }

            } else {
                workOrderHistoryService.updateHandleStatus(request.getOrderNo(),1,request.getCompletedTime());
                LambdaUpdateWrapper<AppealLog> selectWrapper = new LambdaUpdateWrapper<>();
                selectWrapper.eq(AppealLog::getWorkorderId,history.getId()).eq(AppealLog::getIsDeleted,0);
                List<AppealLog> appealLogList = appealLogService.list(selectWrapper);
                LambdaUpdateWrapper<AppealLog> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.eq(AppealLog::getWorkorderId,history.getId()).eq(AppealLog::getIsDeleted,0);
                AppealLog alarmApplyLog = new AppealLog();
                alarmApplyLog.setAppealStatus(APPEAL_STATUS_3);
                alarmApplyLog.setAppealResult(request.getCompleteResult());
                alarmApplyLog.setUpdatedAt(new Date());
                boolean result1 = appealLogService.update(alarmApplyLog,updateWrapper);
                if (!CollectionUtils.isEmpty(appealLogList)) {
                    alarmApplyLog.setAppealType(appealLogList.get(0).getAppealType());
                }
                if (history.getConsumerId() > 0) {
                    LambdaUpdateWrapper<Consumer> consumerWrapper = new LambdaUpdateWrapper<>();
                    consumerWrapper.or().eq(Consumer::getId, history.getConsumerId())
                            .set(Consumer::getStatus, 0);
                    consumerService.update(consumerWrapper);
                }
                log.info("工单处理完成，更新报警器设备报警诉求记录,结果：{}，内容：{}",result1,alarmApplyLog.toString());
                // 更新报警/故障信息记录主表
                if (alarmApplyLog.getAppealType() == null || alarmApplyLog.getAppealType() == 0) {
                    LambdaUpdateWrapper<HistoryAlarm> historyAlarmWrapper = new LambdaUpdateWrapper<>();
                    historyAlarmWrapper.eq(HistoryAlarm::getWorkorderId,history.getId()).eq(HistoryAlarm::getIsDeleted,0);
                    HistoryAlarm historyAlarm = new HistoryAlarm();
                    historyAlarm.setAppealStatus(alarmApplyLog.getAppealStatus());
                    historyAlarm.setAppealResult(alarmApplyLog.getAppealResult());
                    boolean historyAlarmResult = historyAlarmService.update(historyAlarm,historyAlarmWrapper);
                    log.info("工单处理完成，更新报警器设备报警记录,结果：{}，内容：{}",historyAlarmResult,historyAlarm.toString());
                } else if (alarmApplyLog.getAppealType() == 1) {
                    LambdaUpdateWrapper<HistoryBroken> historyBrokenWrapper = new LambdaUpdateWrapper<>();
                    historyBrokenWrapper.eq(HistoryBroken::getWorkorderId,history.getId()).eq(HistoryBroken::getIsDeleted,0);
                    HistoryBroken historyBroken = new HistoryBroken();
                    historyBroken.setAppealStatus(alarmApplyLog.getAppealStatus());
                    historyBroken.setAppealResult(alarmApplyLog.getAppealResult());
                    boolean historyBrokenResult = historyBrokenService.update(historyBroken,historyBrokenWrapper);
                    log.info("工单处理完成，更新报警器设备故障记录,结果：{}，内容：{}",historyBrokenResult,historyBroken.toString());
                }
                LambdaUpdateWrapper<SmartKitchenLog> queryWrapper2 = new LambdaUpdateWrapper<>();
                queryWrapper2.eq(SmartKitchenLog::getWorkorderId,history.getId()).eq(SmartKitchenLog::getIsDeleted,0);
                List<SmartKitchenLog> list = smartKitchenLogService.list(queryWrapper2);
                if (CollectionUtil.isEmpty(list)) {
                    return;
                }
                SmartKitchenLog smartKitchenLog = list.get(0);
                if (smartKitchenLog != null) {
                    LambdaUpdateWrapper<SmartKitchenLog> updateWrapper2 = new LambdaUpdateWrapper<>();
                    updateWrapper2.eq(SmartKitchenLog::getWorkorderId,history.getId()).eq(SmartKitchenLog::getIsDeleted,0);
                    SmartKitchenLog insertLog = new SmartKitchenLog();
                    insertLog.setId(smartKitchenLog.getId());
                    insertLog.setAppealStatus(APPEAL_STATUS_3);
                    insertLog.setAppealResult(request.getCompleteResult());
                    insertLog.setUpdatedAt(new Date());
                    boolean result2 = smartKitchenLogService.updateById(insertLog);
                    log.info("工单处理完成，更新智慧厨房诉求记录表,结果：{}，内容：{}：", result2, insertLog.toString());
                    if (result2){
                        ConsoleSkUpdateRequest consoleSkUpdateRequest = new ConsoleSkUpdateRequest();
                        consoleSkUpdateRequest.setId(smartKitchenLog.getRecordId());
                        consoleSkUpdateRequest.setDealStatus(3);
                        consoleSkUpdateRequest.setResult("完成");
                        log.info("alarmSOSUpdate-request:{}",JSONObject.toJSONString(consoleSkUpdateRequest));
                        ConsoleSkUpdateResponse consoleSkUpdateResponse = client.alarmSOSUpdate(consoleSkUpdateRequest);
                        log.info("alarmSOSUpdate-consoleSkUpdateResponse:{}",JSONObject.toJSONString(consoleSkUpdateResponse));
                    }
                    LambdaQueryWrapper<ServiceComboOrder> logQueryWrapper = new LambdaQueryWrapper<>();
                    logQueryWrapper.eq(ServiceComboOrder::getThirdOrderNo,request.getOrderNo())
                            .eq(ServiceComboOrder::getThirdOrderId, request.getOrderNo())
                            .eq(ServiceComboOrder::getIsDeleted,0);
                    List<ServiceComboOrder> comboOrders = serviceComboOrderMapper.selectList(logQueryWrapper);
                    if (!CollectionUtils.isEmpty(comboOrders)) {
                        for (ServiceComboOrder comboOrder : comboOrders) {
                            comboOrder.setThirdOrderStatus(request.getCompleteResult());
                            SyncOrderDataRespose dataRespose = new SyncOrderDataRespose();
                            dataRespose.setServiceBeginTime(DateUtils.datetimeFormat(request.getServiceBeginTime()));
                            dataRespose.setServiceEndTime(DateUtils.datetimeFormat(request.getServiceEndTime()));
                            dataRespose.setVisitPerson(request.getVisitPerson());
                            dataRespose.setContact(request.getContact());
                            comboOrder.setThirdOrderExt(JSON.toJSONString(dataRespose));
                            serviceComboOrderMapper.updateById(comboOrder);
                        }
                    }
                }
            }
        }else{
            log.info("未找到相应的工单记录:{}",JSONObject.toJSONString(request));
        }
    }

    @Override
    public Integer spark(OrderSparkOrderRequest request) {
        log.info("入参为：{}",request);
        String spId = request.getSpId();
        spId = dictionaryService.selectNewAsstSpMapping(spId);
        log.info("createOrderConsumerBindImei current use spId:{}",spId);

        String imei = request.getImei();
        if (request.getImei().contains("-")) {
            imei = request.getImei().split("-")[0];
        }
        Dtu dtu = equipmentService.getDeviceByImei(imei, spId);
        if (dtu == null){
            throw new BizException(request.getImei() + "该设备未在报警器平台注册");
        }
        Integer orderType = 11;
        if( null!=request.getOrderType() && request.getOrderType()>0 ){
            orderType = request.getOrderType();
        }
        LambdaUpdateWrapper<WorkOrderHistory> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(WorkOrderHistory::getDeviceId,imei)
                .eq(WorkOrderHistory::getOrderType, orderType)
                .eq(WorkOrderHistory::getIsDeleted,0).eq(WorkOrderHistory::getOrderNo, request.getOrderNo() +"S");
        log.info("工单的sql为{}", queryWrapper.getSqlSegment());
        WorkOrderHistory history = workOrderHistoryService.getOne(queryWrapper);
        if (request.getState() == 1){
            if (history != null){
                queryWrapper.set(WorkOrderHistory::getHandleStatus, 0);
                queryWrapper.set(WorkOrderHistory::getReason, null);
                workOrderHistoryService.update(queryWrapper);
                log.info("设备{}调试中1",imei);
                return 1;
            }
            request.setOrderType(orderType);
            this.createSparkOrder(request,spId);
            log.info("设备{}调试中2",imei);
            return 1;
        }else if (request.getState() == 2){
            queryWrapper.set(WorkOrderHistory::getHandleStatus, 1);
            queryWrapper.set(WorkOrderHistory::getReason, "工单中止");
            workOrderHistoryService.update(queryWrapper);
            log.info("设备{}调试结束",imei);
            return 2;
        }
        return -1;
    }

    @Override
    public Integer sparkStatus(OrderSparkOrderRequest request) {
        log.info("sparkStatus入参为：{}",request);
        String spId = request.getSpId();
        spId = dictionaryService.selectNewAsstSpMapping(spId);
        log.info("sparkStatus current use spId:{}",spId);


        String imei = request.getImei();
        if (request.getImei().contains("-")) {
            imei = request.getImei().split("-")[0];
        }
        Dtu dtu = equipmentService.getDeviceByImei(imei, spId);
        if (dtu == null){
            throw new BizException(request.getImei() + "该设备未在报警器平台注册");
        }
        Integer orderType = 11;
        if( null!=request.getOrderType() && request.getOrderType()>0 ){
            orderType = request.getOrderType();
        }
        LambdaUpdateWrapper<WorkOrderHistory> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(WorkOrderHistory::getDeviceId,imei)
                .eq(WorkOrderHistory::getOrderType, orderType)
                .eq(WorkOrderHistory::getIsDeleted,0).eq(WorkOrderHistory::getOrderNo, request.getOrderNo() +"S");
        log.info("sql为{}", queryWrapper.getSqlSegment());
        WorkOrderHistory history = workOrderHistoryService.getOne(queryWrapper);
        Integer status = 0;//未开始调试
        if (history != null && history.getHandleStatus() == 0){
            status = 1;//调试中
        }else if(history != null && history.getHandleStatus() == 1){
            status = 2;//调试完成
        }
        return status;
    }

    public void createSparkOrder(OrderSparkOrderRequest request,String spId) {
        WorkOrderHistory history = new WorkOrderHistory();
        String woSeq = workOrderHistoryService.WORK_ORDER_NO_PREFIX + SnowflakeUtil.getSnowflakeId();
        history.setWoSeq(woSeq);
        history.setDeviceId(request.getImei());
        history.setOrderNo(request.getOrderNo() +"S");
        history.setSubsCode(request.getSubsCode());
        history.setWorkSystem(0);
        history.setOrderType(request.getOrderType());
        history.setFromSystem(2);
        history.setHandleStatus(0);
        history.setOperatorBy("工单系统");
        history.setOrderChannel(2);
        history.setSpId(spId);
        workOrderHistoryService.save(history);
    }

    @Override
    public void editContacts(ContactsEditRequest request) {
        log.info("延伸业务工单修改联系人入参：{}", request);
        String spId = ApplicationUtils.getHeaderSpId();
        if (StringUtils.isEmpty(spId)) {
            spId = request.getSpId();
        }
        if (StringUtils.isEmpty(spId)) {
            throw new BizException("spId 不能为空");
        }
        spId = dictionaryService.selectNewAsstSpMapping(spId);
        LambdaQueryWrapper<Dtu> dtuLqw = new LambdaQueryWrapper<>();
        dtuLqw.eq(Dtu::getIMEI, request.getImei())
                .eq(Dtu::getSpId, spId)
                .eq(Dtu::getIsDeleted, IS_DELETED_FALSE);
        List<Dtu> dtus = equipmentService.list(dtuLqw);
        if (CollectionUtils.isEmpty(dtus)) {
            throw new BizException("设备IMEI" + request.getImei() + "未在该企业下找到");
        }
        Dtu dtu = dtus.get(0);
        if (0 == dtu.getConsumerId()) {
            throw new BizException("设备IMEI" + request.getImei() + "未绑定客户ID");
        }
        LambdaQueryWrapper<Consumer> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Consumer::getId, dtu.getConsumerId())
                .eq(Consumer::getSpId, spId)
                .eq(Consumer::getIsDeleted, IS_DELETED_FALSE);
        List<Consumer> consumers = consumerService.list(lqw);
        if (CollectionUtils.isEmpty(consumers)) {
            throw new BizException("未找到客户信息");
        }
        syncNewAsstOrderService.doEditContacts(request.getContactsList(),spId,consumers.get(0));
    }

    @Override
    public List<ContactsListResponse> getContactsList(ContactsListRequest request) {
        String spId = ApplicationUtils.getHeaderSpId();
        if (StringUtils.isEmpty(spId)) {
            spId = request.getSpId();
        }
        if (StringUtils.isEmpty(spId)) {
            throw new BizException("spId 不能为空");
        }
        spId = dictionaryService.selectNewAsstSpMapping(spId);
        LambdaQueryWrapper<Dtu> dtuLqw = new LambdaQueryWrapper<>();
        dtuLqw.eq(Dtu::getIMEI, request.getImei())
                .eq(Dtu::getSpId, spId)
                .eq(Dtu::getIsDeleted, IS_DELETED_FALSE);
        List<Dtu> dtus = equipmentService.list(dtuLqw);
        if (CollectionUtils.isEmpty(dtus)) {
            throw new BizException("设备IMEI" + request.getImei() + "未在该企业下找到");
        }
        Dtu dtu = dtus.get(0);
        if (0 == dtu.getConsumerId()) {
            throw new BizException("设备IMEI" + request.getImei() + "未绑定客户ID");
        }
        //获取联系人列表
        QueryWrapper<Contacts> contactsWrapper = new QueryWrapper<>();
        contactsWrapper.lambda().eq(Contacts::getConsumerId, dtu.getConsumerId())
                .eq(Contacts::getLevel, 1)
                .eq(Contacts::getSpId, dtu.getSpId())
                .ne(Contacts::getTag, PhoneTypeEnum.TYPE_0.getCode())
                .like(Contacts::getTag, "asst_%")
                .eq(Contacts::getIsDeleted, Constants.IS_DELETED_FALSE)
                .orderByAsc(Contacts::getTag);
        List<Contacts> contactsList = contactsService.list(contactsWrapper);
        List<ContactsListResponse> resp = BeanConvertUtils.convertListTo(contactsList, ContactsListResponse::new);
        return resp;
    }
}
